﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace DumpCSV
{
    public partial class Form1 : Form
    {
        public Form1 () {
            InitializeComponent();
            InitKeyword();
        }
        private List<string> keywords = new List<string>();

        private void ExportPathBtn_Click (object sender, EventArgs e) {
            OpenFileDialog fb = new OpenFileDialog();
            //fb.Filter = "Code files (*.cs *.shader)|*.cs;*.txt|All files (*.*)|*.*";
            fb.Filter = "All files (*.*)|*.*";
            if (fb.ShowDialog() == DialogResult.OK) ExportPathBox.Text = fb.FileName;
        }
        private void UpdatePathBtn_Click (object sender, EventArgs e) {
            OpenFileDialog fb = new OpenFileDialog();
            fb.Filter = "All files (*.*)|*.*";
            if (fb.ShowDialog() == DialogResult.OK) UpdatePathBox.Text = fb.FileName;
        }

        private void InitKeyword() {
            keywords.Add("Export ");
            keywords.Add(" completed!");
        }
        private bool HaveAllKeywords(string str) {
            foreach (string key in keywords)
                if (str.IndexOf(key) < 0) return false;
            return true;
        }
        private string CutAllKeywords(string str) {
            foreach (string key in keywords)
                str = str.Replace(key, "");
            return str;
        }
        private void ExecuteBtn_Click (object sender, EventArgs e) {
            //BackupFile(ExportPathBox.Text);
            //MessageBox.Show("程序执行完成！");
            string err = UpdateExportLog(ExportPathBox.Text, UpdatePathBox.Text);
            if (err != null) MessageBox.Show("错误：" + err);
            else MessageBox.Show("程序执行完成！");
        }

        private string UpdateExportLog(string exportFile, string updateFile) {
            string err = null;
            Dictionary<string, int> exportDict = new Dictionary<string, int>();
            Dictionary<string, int> updateDict = new Dictionary<string, int>();
            string[] updateLine = File.ReadAllLines(updateFile);
            
            for (int l = updateLine.Length-1; l >= 0; l--) {
                if (updateDict.ContainsKey(updateLine[l])) return "检测到重复资源行:" + l;
                updateDict.Add(updateLine[l], l);
            }

            string[] exportLine = File.ReadAllLines(exportFile);
            foreach (string line in exportLine) {
                if (!HaveAllKeywords(line)) continue;
                string key = CutAllKeywords(line);
                if (!exportDict.ContainsKey(key)) exportDict.Add(key, 0);
            }

            foreach (KeyValuePair<string, int> p in exportDict)
                if (updateDict.ContainsKey(p.Key)) updateDict.Remove(p.Key);

            var list = updateDict.OrderBy(s => s.Value);
            string[] lines = new string[updateDict.Count];
            int i = 0;
            foreach (KeyValuePair<string, int> p in list)
                lines[i++] = p.Key;

            BackupFile(updateFile);
            File.WriteAllLines(updateFile, lines);

            return err;
        }
        private void BackupFile(string file) {
            string[] arr = SplitPath(file);
            string path = arr[0] + arr[1] + "_backup." + arr[2];
            if (!File.Exists(path)) {
                File.Move(file, path);
                return;
            }

            for (int i = 1; i < 100000; i++) {
                path = arr[0] + arr[1] + "_backup (" + i + ")." + arr[2];
                if (!File.Exists(path)) {
                    File.Move(file, path);
                    break;
                }
            }
        }
        private string[] SplitPath(string path) {
            string[] arr = new string[3];
            string name = GetFileName(path);
            if (name == null) return null;
            arr[0] = path.Replace(name, "");

            int idx = name.LastIndexOf('.');
            if (idx > 0) {
                arr[1] = name.Substring(0, idx);
                arr[2] = name.Substring(idx+1);
            } else if (idx < 0) {
                arr[1] = name;
                arr[2] = "";
            }
            return arr;
        }

        private string GetFileName(string path) {
            int idxWin = path.LastIndexOf('\\');
            int idxUinux = path.LastIndexOf('/');
            int idx = Math.Max(idxWin, idxUinux);
            if (idx < 0) return null;
            return path.Substring(idx);
        }

        private string RemoveSuffix (string name) {
            int idx = name.LastIndexOf('.');
            if (idx < 0) return null;
            return name.Substring(0, idx);
        }

        private bool TypeInFilter(string file, string filter) {
            string[] types = filter.Split(',');
            string ft = GetType(file);
            if (ft == null) return false;

            foreach (string type in types) {
                if (type == ft) return true;
            }
            return false;
        }
        private string GetType(string path) {
            int idx = path.LastIndexOf('.');
            if (idx < 0) return null;
            return path.Substring(idx + 1, path.Length - (idx + 1));
        }

    }
}
